#include "Dialog_addCandidates.h"
#include "ui_Dialog_addCandidates.h"
#include "dbOperate/sqliteoperate.h"
#include "dbOperate/dbPrescription.h"

Dialog_addCandidates::Dialog_addCandidates(QWidget *parent) :
	QDialog(parent),
	ui(new Ui::Dialog_addCandidates)
{
	ui->setupUi(this);
	initInterface();
}

Dialog_addCandidates::~Dialog_addCandidates()
{
	delete ui;
}

void Dialog_addCandidates::refreshTable()
{
	ui->tableWidget->setRowCount(0);
	ui->tableWidget->clearContents();
	QList<default_list_t> lists;
	lists = dp.getMedicineLists();
	for (int i=0; i<lists.length(); i++) {
		ui->tableWidget->insertRow(i);
		QTableWidgetItem* itemName = new QTableWidgetItem(lists.at(i).name);
		itemName->setData(Qt::UserRole, lists.at(i).id);
		ui->tableWidget->setItem(i, 0, itemName);
		QTableWidgetItem* itemDefaultSum = new QTableWidgetItem(QString::number(lists.at(i).default_sum));
		ui->tableWidget->setItem(i, 1, itemDefaultSum);
		QTableWidgetItem* itemUnit = new QTableWidgetItem(lists.at(i).unit);
		ui->tableWidget->setItem(i, 2, itemUnit);
	}
	ui->tableWidget->setColumnWidth(0, 300);
	ui->tableWidget->setColumnWidth(1, 80);
}

void Dialog_addCandidates::initInterface()
{
	refreshTable();
	//ui->tableWidget->setColumnWidth(2, 80);

	QList<QAction*> actions;

	QAction* act0 = new QAction("删除");
	connect(act0, SIGNAL(triggered(bool)), this, SLOT(delete_record()));
	actions.append(act0);
	menu.addActions(actions);

}

void Dialog_addCandidates::on_pushButton_add_clicked()
{
	QString name	 = ui->lineEdit_name->text();
	if (name.length() == 0) {
		QMessageBox::critical(this, "添加默认选项失败", "未输入名称");
		return;
	}
	int default_sum  = ui->spinBox_sum->value();
	QString unit	 = ui->lineEdit_unit->text();
	if (unit.length() == 0) {
		QMessageBox::critical(this, "添加默认选项失败", "未输入单位");
		return;
	}
	sqliteOperate sl;
	if (sl.openDataBase(DBName)){
		dbPrescription dp;
		if (dp.addMedicineList(name, default_sum, unit)){
			refreshTable();
		}
		else {
			QMessageBox::warning(this, "添加选项", "添加选项失败");
		}
	}


}

/// 右键菜单
void Dialog_addCandidates::on_tableWidget_customContextMenuRequested(const QPoint &pos)
{
	this->menu.exec(QCursor::pos());
}

///
/// \brief Dialog_addCandidates::delete_record
///删除
void Dialog_addCandidates::delete_record()
{
	int id = ui->tableWidget->item(ui->tableWidget->currentRow(), 0)->data(Qt::UserRole).toInt();
	qDebug()<<"gonna delete medicine list, id:"<<id;
	if (!dp.removeMedicineList(id)) {
		QMessageBox::information(this, "删除默认选项", "删除默认选项失败!");
	}
	refreshTable();
}
